var app = new Vue({
  el: "#app",
  data: {
    map: null,
    markerList: [],
    dataList: [],
    level: "enterprise", // 数据级别 province: 省级 city: 市级 enterprise: 企业
    provinceLevel: 1, // 省级数据级别
    cityLevel: 6, // 市级数据级别
    enterpriseLevel: 8, // 企业数据级别
    timer: null, // 定时器
    userLocation: [116.39, 39.9], // 用户位置 [经度, 纬度] 默认值 北京
    keyword: "", // 搜索关键词
    searchResult: [], // 搜索结果
    detailList: [], // 详情信息
    detailCopy: [], // 详情信息
    showDialog: false, // 显示弹窗
    form: {
      name: "", // 姓名
      phone: "", // 手机号
    },
    rule: {
      name: [{ required: true, message: "请输入联系人姓名", trigger: "blur" }],
      phone: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        {
          pattern: /^1[3456789]\d{9}$/,
          message: "请输入正确的手机号",
          trigger: "blur",
        },
      ],
    },
    formMessage: {
      uid: "",
      name: "", // 姓名
      phone: "", // 手机号
      desc: "",
    },
    ruleMessage: {
      name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
      phone: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        {
          pattern: /^1[3456789]\d{9}$/,
          message: "请输入正确的手机号",
          trigger: "blur",
        },
      ],
      desc: [{ required: true, message: "请输入补充内容", trigger: "blur" }],
    },

    loadingSubmit: false, // 提交中
    markerZindexCopy: 1,
    activeMarketId: "", // 当前标记id
    activeMarket: null, // 当前标记id
    showButton: false, // 显示按钮
    showType: "detail",
    // 留言
    showDialogMessage: false,
  },
  mounted() {
    this.initMap();
  },
  methods: {
    // 后退
    handleBack() {
      history.back();
    },
    // 初始化地图
    initMap() {
      this.map = new AMap.Map("mapContainer", {
        resizeEnable: true,
        zoom: this.enterpriseLevel,
        // center: [106, 35], // 中心点 北京
        // zoom: this.enterpriseLevel,
        // center: [114.4839, 38.0353],  // 中心点 石家庄
      });
      // 在初始化地图时，如果center属性缺省，地图默认定位到用户所在城市的中心
      this.userLocation = [this.map.getCenter().lng, this.map.getCenter().lat];
      const _this = this;

      // 定位控件
      AMap.plugin("AMap.Geolocation", function () {
        var geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, // 是否使用高精度定位，默认：true
          timeout: 10000, // 设置定位超时时间，默认：无穷大
          offset: [10, 20], // 定位按钮的停靠位置的偏移量
          zoomToAccuracy: true, //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          position: "RT", //  定位按钮的排放位置,  RB表示右下
        });
        geolocation.getCurrentPosition(function (status, result) {
          if (status == "complete") {
            onComplete(result);
          } else {
            onError(result);
          }
        });

        function onComplete(data) {
          // data是具体的定位信息
          console.log("onComplete", data);
          this.userLocation = [data.position.lng, data.position.lat];
        }

        function onError(data) {
          // 定位出错
          console.error("onError", data);
        }

        _this.map.addControl(geolocation); //添加控件
      });

      this.$nextTick(() => {
        this.getInfo();
      });
    },
    // 获取信息
    getInfo() {
      apiGetInfo().then((res) => {
        const { data } = res;
        if (data) {
          // 过滤没有经纬度的企业
          data.enterprise = data.enterprise.filter((item) => {
            return item.altX && item.altY;
          });
          // 计算距离
          data.enterprise.forEach((item) => {
            item.distance = this.getDistance([item.altX, item.altY]);
          });
          // 排序
          data.enterprise.sort((a, b) => {
            return a.distance - b.distance;
          });
          // 计算省市总数
          const total = this.getTotalCount(data.enterprise);
          data.province = total.province;
          data.city = total.city;
          console.log(data);

          this.dataList = data;
          // 距离最短的一个企业
          this.getDetail(data.enterprise[0].uid);
          // 地图设置到距离最短的一个企业
          this.map.setCenter(
            [data.enterprise[0].altX, data.enterprise[0].altY],
            true
          );
          if (parseInt(data.is_join) === 0) {
            this.showButton = true;
          }
          this.map.on("zoomchange", this.mapZoom);
          this.map.on("mapmove", this.mapMove);
          this.setMarker();
        }
      });
      // .catch((err) => {
      //   vant.Toast.fail((err && err.msg) || err);
      // });
    },
    // 计算省市总数
    getTotalCount(list) {
      // 根据provlonglat，citylonglat汇总省市的数量
      const provinceList = [];
      const cityList = [];
      list.forEach((item) => {
        const { provlonglat, citylonglat } = item;
        if (provinceList.every((item) => item.name !== provlonglat)) {
          provinceList.push({
            name: provlonglat,
            pos: provlonglat.split(","),
            value: 1,
          });
        } else {
          provinceList.forEach((item) => {
            if (item.name === provlonglat) {
              item.value++;
            }
          });
        }
        if (cityList.every((item) => item.name !== citylonglat)) {
          cityList.push({
            name: citylonglat,
            pos: citylonglat.split(","),
            value: 1,
          });
        } else {
          cityList.forEach((item) => {
            if (item.name === citylonglat) {
              item.value++;
            }
          });
        }
      });
      return {
        province: provinceList,
        city: cityList,
      };
    },
    // 设置标记
    setMarker() {
      this.map.remove(this.markerList);
      this.markerList = [];
      if (this.level === "enterprise") {
        const bounds = this.map.getBounds();
        const southWest = bounds.getSouthWest(); // 左下角
        const northEast = bounds.getNorthEast(); // 右上角
        const add = 0.1;
        this.dataList.enterprise.forEach((item) => {
          const { uid, comname, altX, altY } = item;
          if (
            altX < southWest.lng - add ||
            altX > northEast.lng + add ||
            altY < southWest.lat - add ||
            altY > northEast.lat + add
          ) {
            return;
          }
          const marker = new AMap.Marker({
            position: new AMap.LngLat(altX, altY),
            content: `<div class="map-marker-box1"  data-id="${uid}">
            <div class="map-marker-title">
            <p class="ellipsis"> ${comname} </p>
            </div>
            <div class="map-marker-point"></div>
             </div>`,
            extData: { uid },
            anchor: "bottom-center",
          });
          if (this.activeMarketId === uid) {
            this.setActiveMarket(marker);
          }
          marker.on("click", this.onMarkerClick);
          this.markerList.push(marker);
        });
      } else {
        this.dataList[this.level].forEach((item) => {
          const { name, pos, value } = item;
          const marker = new AMap.Marker({
            position: new AMap.LngLat(pos[0], pos[1]),
            content: `<div class="map-marker-box">
               ${value}
            </div>`,
            anchor: "center",
          });
          marker.on("click", this.onMarkerClick);
          this.markerList.push(marker);
        });
      }
      this.map.add(this.markerList);
    },
    // 地图缩放
    mapZoom() {
      const mapZoom = this.map.getZoom();
      if (mapZoom < this.cityLevel) {
        // 显示省级数据
        if (this.level !== "province") {
          this.level = "province";
          this.setMarker();
        }
      } else if (mapZoom >= this.cityLevel && mapZoom < this.enterpriseLevel) {
        // 显示市级数据
        if (this.level !== "city") {
          this.level = "city";
          this.setMarker();
        }
      } else if (mapZoom >= this.enterpriseLevel) {
        // 显示企业名称
        if (this.level !== "enterprise") {
          this.level = "enterprise";
          this.setMarker();
        }
      }
    },
    // 地图移动
    mapMove() {
      if (this.level === "enterprise") {
        this.setMarker();
      }
    },
    // 点击标记
    onMarkerClick(e) {
      if (this.level === "province") {
        this.map.setZoomAndCenter(this.cityLevel, e.lnglat, false, 800);
      } else if (this.level === "city") {
        this.map.setZoomAndCenter(this.enterpriseLevel, e.lnglat, false, 800);
      } else if (this.level === "enterprise") {
        this.map.setCenter(e.lnglat, false, 300);
        const uid = e.target.getExtData().uid;
        this.setActiveMarket(e.target);
        this.getDetail(uid);
      }
    },
    // 设置当前标记
    setActiveMarket(marker) {
      if (this.activeMarket) {
        this.activeMarket.setzIndex(12);
        this.activeMarket.setContent(
          this.activeMarket
            .getContent()
            .replace(
              "map-marker-box1 map-marker-box1-active",
              "map-marker-box1"
            )
        );
      }
      this.activeMarket = marker;
      this.activeMarket.setzIndex(100);
      this.activeMarket.setContent(
        this.activeMarket
          .getContent()
          .replace("map-marker-box1", "map-marker-box1 map-marker-box1-active")
      );
      this.activeMarketId = this.activeMarket.getExtData().id;
    },
    // 点击企业
    onCompanyClick(item) {
      this.activeMarketId = item.uid;
      this.level = "enterprise";
      this.map.setZoomAndCenter(
        this.enterpriseLevel,
        new AMap.LngLat(item.altX, item.altY),
        false,
        300
      );
      this.getDetail(item.uid);
    },
    // 获取企业详情
    getDetail(uid) {
      this.showType = "detail";
      this.dataList.enterprise.forEach((item) => {
        if (item.uid === uid) {
          this.detailCopy = this.detailList = [item];
        }
      });
    },
    // 两个经纬度之间的距离
    getDistance(pos) {
      let distance = AMap.GeometryUtil.distance(this.userLocation, pos) / 1000; // 计算出的是两点的距离，单位为米
      distance = Math.round(distance * 10) / 10; // 保留小数1位
      return distance;
    },
    // 搜索
    onSearch(e) {
      if (e) {
        e.preventDefault();
      }
      if (e.keyCode === 13) {
        if (this.keyword.trim() === "") {
          vant.Toast("请输入搜索内容");
          return;
        }
        this.detailList = [];
        this.showType = "search";
        this.detailList = this.dataList.enterprise.filter((item) => {
          return item.comname.indexOf(this.keyword) > -1;
        });
        // 收起键盘
        document.getElementById("inputSearch").blur();
      }
    },
    // 申请入驻
    onApply() {
      this.showDialog = true;
    },
    // 提交申请
    onSubmit() {
      if (this.loadingSubmit) {
        return;
      }
      if (this.validate(this.form, this.rule)) {
        this.loadingSubmit = true;
        apiSubmit(this.form)
          .then((res) => {
            vant.Toast.success("提交成功");
            setTimeout(() => {
              this.showDialog = false;
              this.loadingSubmit = false;
              // 清空表单
              this.form = {
                name: "",
                phone: "",
              };
            }, 1000);
          })
          .catch((err) => {
            vant.Toast.fail((err && err.msg) || err);
            this.loadingSubmit = false;
          });
      }
    },
    // 提交留言
    onSubmitMessage() {
      if (this.loadingSubmit) {
        return;
      }
      if (this.validate(this.formMessage, this.ruleMessage)) {
        this.loadingSubmit = true;
        apiLeavaMessage(this.formMessage)
          .then((res) => {
            vant.Toast.success("提交成功");
            setTimeout(() => {
              this.showDialogMessage = false;
              this.loadingSubmit = false;
            }, 1000);
          })
          .catch((err) => {
            vant.Toast.fail((err && err.msg) || err);
            this.loadingSubmit = false;
          });
      }
    },
    // 表单验证
    validate(form, rule) {
      let rersult = true;
      for (let key in rule) {
        rule[key].forEach((item) => {
          if (rersult) {
            if (item.required && !form[key].trim()) {
              vant.Toast(item.message);
              rersult = false;
            }
            if (item.pattern && !item.pattern.test(form[key])) {
              vant.Toast(item.message);
              rersult = false;
            }
          }
        });
      }
      return rersult;
    },
    // 在线询盘
    handleInquiry(item) {
      if (parseInt(item.ischat) === 1) {
        // 有在线了聊天权限，跳转在线聊天
        location.href = `https://m.feijiu.net/chatm/${item.shopimuid}.html`;
      } else {
        // 没有在线聊天权限，显示留言框
        this.formMessage.uid = item.uid;
        // 获取登录用户信息
        apiGetUserInfo()
          .then((res) => {
            const { name, phone } = res.data;
            this.formMessage.name = name;
            this.formMessage.phone = phone;
            this.showDialogMessage = true;
          })
          .catch((err) => {
            this.showDialogMessage = true;
          });
      }
    },
    handleClear() {
      this.keyword = "";
      this.showType = "detail";
      this.detailList = this.detailCopy;
      document.getElementById("inputSearch").blur();
    },
  },
});
